package com.fable.sp.core.config;

import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.core.type.classreading.MethodMetadataReadingVisitor;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;

/**
 * .
 *
 * @author stormning on 16/7/19.
 */
public class MissingBeanCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        ConfigurableListableBeanFactory factory = context.getBeanFactory();
        String returnTypeName = ((MethodMetadataReadingVisitor) metadata).getReturnTypeName();
        Class<?> aClass = ClassUtils.resolveClassName(returnTypeName, factory.getBeanClassLoader());
        String[] names = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(factory, aClass, false, false);
        return ObjectUtils.isEmpty(names);
    }
}
